﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LSQL;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;

namespace Shopfloormanagement.Forms
{
    public partial class meetingCreateForm : DevExpress.XtraEditors.XtraForm
    {
        public static meetingCreateForm instance = new meetingCreateForm();
        public meetingCreateForm()
        {
            instance = this;
            InitializeComponent();
        }
        private DataTable dtMember = new DataTable();
        private void meetingCreateForm_Load(object sender, EventArgs e)
        {
            lbLevel.Text = "Meeting level: ";
            lbDep.Text = "Department: ";

            lbLevel.Text += $" {SystemInfo.readLevel}";
            if (SystemInfo.readLevel == publicFunc.MaxDepartmentLevel())
            {
                //最高等级，部门显示为工厂
                lbDep.Text = $"Factory: {SystemInfo.readFactoryName}";
            }
            else
            {
                lbDep.Text = $"Department: {SystemInfo.readparentDepName}";
            }
            LoadEmployee();

            dtMember = new DataTable();
            dtMember.Columns.Add("ID", typeof(int));
            dtMember.Columns.Add("FullName", typeof(string));
            dtMember.Columns.Add("LoginName", typeof(string));

            if (DevMainForm.MeetingId != 0)
            {
                MeetingID = DevMainForm.MeetingId;
                DataTable res = SQL.ReturnDataTable3(SystemInfo.SQL, "Meeting", $"ID = {DevMainForm.MeetingId}");
                string Condition = $"ID in({res.Rows[0]["MeetingMember"]})";
                dtMember = SQL.ReturnDataTableDist(SystemInfo.SQL,"ID,FullName,LoginName","Employees",Condition);

            }

            gcMember.DataSource = dtMember;
            gvMember.Columns["ID"].Visible = false;
            gvMember.Columns["FullName"].OptionsColumn.AllowEdit = false;
            gvMember.Columns["LoginName"].OptionsColumn.AllowEdit = false;

        }

        private void LoadEmployee()
        {
            DataTable dtEmployee = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", $"Del_tag = 0");
            publicFunc.ComboBoxInit(dtEmployee, cbMember, "FullName", "ID");

        }

        private void meetingCreateForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (memberID != 0)
            {
                DataTable res = SQL.ReturnDataTableDist(SystemInfo.SQL, "ID,FullName,LoginName", "Employees", $"ID = {memberID}");
                if (res.Rows.Count > 0)
                {

                    int ID = (int)res.Rows[0]["ID"];
                    string Full = res.Rows[0]["FullName"].ToString();
                    string Login = res.Rows[0]["LoginName"].ToString();
                    dtMember.Rows.Add(ID, Full, Login);
                    gcMember.RefreshDataSource();
                }

            }
        }

        private int memberID;
        private void cbMember_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbMember.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                memberID = Convert.ToInt32(tag);
            }
        }

        private int MeetingID;
        public static string memberArray;
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            
            if (gvMember.RowCount > 0)
            {
                int[] idsArray = new int[gvMember.RowCount];
                //写入信息
                for (int i = 0; i < gvMember.RowCount; i++)
                {
                    idsArray[i] = Convert.ToInt32(gvMember.GetRowCellValue(i, "ID"));

                }
                string ids = string.Join(",", idsArray);
                DataTable dtMeeting = SQL.ReturnDataTable3(SystemInfo.SQL, "Meeting", $"ID = {MeetingID} and Del_tag = 0");
                if (dtMeeting.Rows.Count > 0)
                {
                    int removeCount = 0;
                    string removedID = "";
                    int[] idPrevious = dtMeeting.Rows[0]["MeetingMember"].ToString().Split(',').Select(int.Parse).ToArray();
                    if (idPrevious.Length > idsArray.Length)
                    {
                        var removed = idPrevious.Except(idsArray).ToArray();
                        removedID = string.Join(",", removed);
                        removeCount = removed.Length;
                    }
                    
                    //Update
                    bool result = SQL.Update(SystemInfo.SQL, "Meeting", $"MeetingMember = '{ids}'", $"ID = {MeetingID}");
                    if (result)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功写入");
                        //判断一下是多是少
                        if (removeCount > 0)
                        {
                            bool delRecord = SQL.Update(SystemInfo.SQL, "MeetingAttendance", "Del_tag = 1", $"MeetingID = {MeetingID} and MemberID in ({removedID})");
                            if (delRecord)
                            {
                                XtraMessageBox.Show(LookAndFeel, $"成功删除记录");
                            }
                        }

                    }
                }
                else
                {
                    int res = SQL.InsertReturnID(SystemInfo.SQL, "Meeting", "MeetingLevel,MeetingDepartmentID,MeetingMember", $"{SystemInfo.readLevel},{SystemInfo.readparentDep},'{ids}'");
                    if (res > 0)
                    {
                        MeetingID = res;
                        //生成本周签到语句
                        for (int i = 0; i < gvMember.RowCount; i++)
                        {
                            int result = SQL.Insert(SystemInfo.SQL, "MeetingAttendance", "MeetingID,MemberID,Year,Week", $"{MeetingID},{idsArray[i]},DATEPART(YEAR, GETDATE()),DATEPART(ISO_WEEK, GETDATE())");
                            Console.WriteLine(res);
                        }
                        XtraMessageBox.Show(LookAndFeel, $"成功写入");
                    }
                }

            }
        }

        private void barItemBtnDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (rowHandle != -1)
            {
                gvMember.DeleteSelectedRows();
            }
        }

        private int deletID = 0;
        private int rowHandle = -1;
        private void gvMember_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);
                if (hitInfo.InRow || hitInfo.InRowCell)
                {
                    rowHandle = hitInfo.RowHandle;
                    deletID = (int)gvMember.GetRowCellValue(rowHandle, "ID");
                    popupMenu1.ShowPopup(Control.MousePosition);
                }
            }
        }
    }
}